package com.jsbj.tools;

import com.alibaba.fastjson.JSONObject;
import com.jsbj.Excel.CustomException;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
@Lazy(false)
public class ContextUtil implements ApplicationContextAware {
    private static ApplicationContext APPLICATION_CONTEXT;

    /**
     * 设置spring上下文  *  * @param applicationContext spring上下文  * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        APPLICATION_CONTEXT = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return APPLICATION_CONTEXT;
    }


    public static List<Map> getFromClassMethod(String className, String methodName, JSONObject param) {
        List<Map> selectDataList = new ArrayList<>();
        try {
            Object bean = ContextUtil.getApplicationContext().getBean(className);//注意beanName为小写
            Class<?> clz = bean.getClass();
            Method m = clz.getDeclaredMethod(methodName, JSONObject.class);
            // 调用方法
            selectDataList = (List) m.invoke(bean, param);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
            throw new CustomException(e.getMessage(), e.getCause());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            throw new CustomException(e.getMessage(), e.getCause());
        } catch (InvocationTargetException e) {
            e.printStackTrace();
            throw new CustomException(e.getMessage(), e.getCause());
        }
        return selectDataList;
    }
}
